# from object.models import User
# from object.database import db
import hashlib
import json
from handle.logger import logger
from handle.S2Redis import sync_data_background,render_template,redis_client,socketio
from flask import session
from object.database import db
from object.models import User
def get_user_cache(hex):
    logger.info("get user cache")
    # value=str(redis_client.get("user").decode('utf-8')).replace("'",'"')
    value = json.loads(redis_client.get("user").decode('utf-8'))
    logger.error(value)
    for key in value:
        if key['UserName'] == hex:
            return key
    return None

def set_session(username,id):
    global session
    if session.get('username')==None and session.get('id')==None:
        session['username']=username
        session['id']=id
        session.permanent = True
        return True
    else:
        return False
    
def del_session():
    global session
    if check_session():
        session.pop('username')
        session.pop('id')
        return True
    else:
        return False

def check_session():
    global session
    return False if (session.get('username')==None and session.get('id')==None) else True

def resetps(username,passwd):
    try:
        us=User.query.filter_by(UserName=username).all()[0]
        us.Password=passwd
        db.session.commit()
        sync_data_background()
        return True
    except Exception as e:
        db.session.rollback()  # 回滚事务以防止部分插入
        logger.error(f"创建商品时发生错误：{e}")
        raise
    